package thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockTryLockTest implements Runnable {
    public static void main(String[] args) {
        ReentrantLockTryLockTest reentrantLockTryLockTest = new ReentrantLockTryLockTest();
        Thread zhangsan = new Thread(reentrantLockTryLockTest, "张三");
        ReentrantLockTryLockTest reentrantLockTryLockTest1 = new ReentrantLockTryLockTest();
        Thread lisi = new Thread(reentrantLockTryLockTest1, "lisi");
        zhangsan.start();
        lisi.start();

    }

    static ReentrantLock reentrantLock = new ReentrantLock();
    @Override
    public void run() {
        try {
            if (reentrantLock.tryLock(5,TimeUnit.SECONDS)){
                System.out.println(Thread.currentThread().getName()+":获取锁成功");
                TimeUnit.SECONDS.sleep(60);
            }else {
                System.out.println(Thread.currentThread().getName()+"：获取锁失败!");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            if (reentrantLock.isHeldByCurrentThread()){
                reentrantLock.unlock();
            }
        }
    }

}
